﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Possan.MySQL.SqlServerCodeGenerator
{
	class ProjectLoader
	{
		public string Filename;

		public void Run()
		{
			Console.WriteLine("Loading " + Filename);

			XmlDocument d = new XmlDocument();
			d.Load(Filename);

			XmlNodeList nl = d.SelectNodes("projects/project");
			foreach (XmlNode n in nl)
				RunProject(n);
		}

		public void RunProject(XmlNode projectnode)
		{
			Generator gen = new Generator();

			if (projectnode.Attributes["connectionstring"] != null)
				gen.ConnectionString = projectnode.Attributes["connectionstring"].Value;

			if (projectnode.Attributes["outputfile"] != null)
				gen.OutputFile = projectnode.Attributes["outputfile"].Value;

			if (projectnode.Attributes["lowercase"] != null)
				gen.LowercaseNames = true;
			
			bool first = true;

			XmlNodeList tablenodes = projectnode.SelectNodes("table");
			foreach (XmlNode tablenode in tablenodes)
			{
				gen.Overwrite = first;

				if (tablenode.Attributes["name"] != null)
					gen.Table = tablenode.Attributes["name"].Value;

				foreach( XmlNode n in tablenode.SelectNodes("exclude") )
				{
					if (n.Attributes["column"] != null)
						gen.ExcludeFields.Add(n.Attributes["column"].Value);
				}

				foreach (XmlNode n in tablenode.SelectNodes("include"))
				{
					if (n.Attributes["column"] != null)
						gen.IncludeFields.Add(n.Attributes["column"].Value);
				}

				gen.Limit = 0;
				if (tablenode.Attributes["top"] != null)
					gen.Limit = ParseInt( tablenode.Attributes["top"].Value );

				if (tablenode.Attributes["includedelete"] != null)
					gen.IncludeDeletes = ParseBool( tablenode.Attributes["includedelete"].Value );

				gen.Run();
				first = false;
			}
		}



		bool ParseBool(string input)
		{
			bool ret = false;
			bool.TryParse(input, out ret);
			return ret;
		}

		int ParseInt(string input)
		{
			int ret = 0;
			int.TryParse(input, out ret);
			return ret;
		}

	}
}
